package com.andy.contentcenter.service.impl;

import com.andy.contentcenter.domain.dto.ShareDTO;
import com.andy.contentcenter.domain.entity.Share;
import com.andy.contentcenter.domain.entity.User;
import com.andy.contentcenter.feignclient.UserCenterFeignClient;
import com.andy.contentcenter.mapper.ShareMapper;
import com.andy.contentcenter.service.ShareService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * 分享表 服务实现类
 * </p>
 *
 * @author Andy
 * @since 2019-08-12
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareServiceImpl extends ServiceImpl<ShareMapper, Share> implements ShareService {

    private final ShareMapper shareMapper;
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;
    private final UserCenterFeignClient userCenterFeignClient;
    @Override
    public ShareDTO findById(Integer id) {
        //获取分享详情
        Share share =this.shareMapper.selectById(id);
        //发布人ID
        Integer userId =share.getUserId();
        //通过Nacos客户端获取实例，然后获取调用地址，然后请求接口
        /**
        List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
        String targetURL = instances.stream().map(instance -> instance.getUri().toString()+"/user/{id}")
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException(""+id));
        log.info("请求的目标地址：{}",targetURL);
        User user = this.restTemplate.getForObject(targetURL,User.class,userId);*/
        //通过 restTemplate 直接使用接口地址 请求
        //User user = this.restTemplate.getForObject("http://user-center/user/{userId}",User.class,userId);
        User user = this.userCenterFeignClient.findById(userId);

        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share, shareDTO);
        shareDTO.setWxNickname(user.getWxNickname());
        return shareDTO;
    }
}
